﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Scene_Manager : MonoBehaviour
{
    private AsyncOperation async;
    private int nowProcess;
    private string sceneName;

    UIManager UIManager;
    void Awake()
    {
        NotifacitionCenter.GetInstance().registerObserver(NotifyType.ENTER_MAP, on_ENTER_MAP);
        NotifacitionCenter.GetInstance().registerObserver(NotifyType.ENTER_KITCHEN, on_ENTER_KITCHEN);

        UIManager = GetComponent<UIManager>();
    }

    void on_ENTER_MAP(NotifyEvent e)
    {
        StartCoroutine(LoadScene("MapScene"));
    }
    void on_ENTER_KITCHEN(NotifyEvent e)
    {
        LevelData levelData = (LevelData)e.Params["levelData"];

        Debug.Log(levelData.id);
        
        StartCoroutine(LoadScene("KitchenScene"));
    }
    
    IEnumerator LoadScene(string sceneName)
    {
        this.sceneName = sceneName;
        nowProcess = 0;
        async = SceneManager.LoadSceneAsync(sceneName);
        async.allowSceneActivation = false;
        yield return async;
    }

    void Update()
    {
        if (async == null)
        {
            return;
        }

        if (async.allowSceneActivation == true)
        {
            return;
        }

        int toProcess;
        // async.progress 你正在读取的场景的进度值  0---0.9    
        // 如果当前的进度小于0.9，说明它还没有加载完成，就说明进度条还需要移动    
        // 如果，场景的数据加载完毕，async.progress 的值就会等于0.9  
        if (async.progress < 0.9f)
        {
            toProcess = (int)async.progress * 100;
        }
        else
        {
            toProcess = 100;
        }
        // 如果滑动条的当前进度，小于，当前加载场景的方法返回的进度   
        if (nowProcess < toProcess)
        {
            nowProcess = nowProcess + 2;
        }

        if (sceneName == "KitchenScene")
        {
            //UIManager.LoadingPanel.gameObject.SetActive(true);
            //UIManager.LoadingPanel.slider.value = nowProcess;
            
        }

        // 设置为true的时候，如果场景数据加载完毕，就可以自动跳转场景   

        if (nowProcess >= 100)
        {
            
            async.allowSceneActivation = true;
            if (sceneName == "MapScene")
            {
                //NotifyEvent e = new NotifyEvent(NotifyType.MAPSCENE_LOAD_COMPLETE, null, this);
                //NotifacitionCenter.GetInstance().postNotification(e);
            }
            else if (sceneName == "KitchenScene")
            {
                //NotifyEvent e = new NotifyEvent(NotifyType.KITCHEN_SCENE_LOAD_COMPLETE, null, this);
                //NotifacitionCenter.GetInstance().postNotification(e);
            }
            
        }
    }
}
